package com.kaili.basic.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.mapper.BaseRoleMapper;
import com.kaili.basic.mapper.BaseUserMapper;
import com.kaili.basic.pojo.entity.BaseCompany;
import com.kaili.basic.service.BaseUserService;
import com.kaili.common.entity.BaseRole;
import com.kaili.common.entity.BaseUser;
import com.kaili.common.util.HexStringUtils;
import com.kaili.common.util.SHA256Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class BaseUserServiceImpl implements BaseUserService {

    @Autowired
    BaseUserMapper baseUserMapper;
    @Autowired
    BaseRoleMapper baseRoleMapper;

    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return baseUserMapper.loadUserByUsername(s);
    }

    public int baseUserReg(BaseUser baseUser, int type) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        BaseUser baseUser1 = baseUserMapper.loadUserByUsername(baseUser.getUsername());
        if (baseUser1 == null) {
            return -1;
        }
       /* if(type==1) {
            if (!encoder.matches(baseUser.getOldpassword(), baseUser1.getPassword())) {
                return -1;
            }
        }*/
        String pwd = baseUser.getPassword();//密码
        String npwd = baseUser.getPassword();//用来循环的密码；
        String encode = hexpwd(pwd, npwd);
        baseUser.setPassword(encode);
        baseUser.setEnabled(true);
        return baseUserMapper.updateBaseUser(baseUser);
    }

    public int baseUserReg2(BaseUser baseUser) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        BaseUser baseUser1 = baseUserMapper.loadUserByUsername(baseUser.getUsername());
        if (baseUser1 == null) {
            return -1;
        }
        String pwd = baseUser.getPassword();//密码
        String npwd = baseUser.getPassword();//用来循环的密码；
        String decode = HexStringUtils.fromHex(baseUser1.getPassword());//还原16进的密码
        String hashd = decode.substring(0, decode.length() - 64);//去掉后面64位hash算法
        String hashe = hashd.substring(hashd.length() - 3, hashd.length());//截取后3位 随机次数
        System.out.println(hashd);
        System.out.println(hashe);
        String salt = hashd.substring(2, 8);//保留salt
        System.out.println(salt);
        int cycletimes = Integer.parseInt(hashe);
        String hexpwd = hexpwd1(pwd, npwd, salt, cycletimes);//
        if (hexpwd.equalsIgnoreCase(baseUser1.getPassword())) {
            return 0;
        } else {
            return -1;
        }
    }

    @Override
    public int addUser(BaseUser user) {
        BaseUser baseUser1 = baseUserMapper.loadUserByUsernameExit(user);
        if (baseUser1 != null) {
            return -1;
        }
        return baseUserMapper.addUser(user);
    }

    public Page<BaseUser> getBaseUsersByKeywords(Page<BaseUser> page, BaseUser baseUser) {
        List<BaseUser> baseUsers = baseUserMapper.getBaseUsersByKeywords(page, baseUser);
        for(int i=0;i<baseUsers.size();i++){
            Integer uid = baseUsers.get(i).getId();
            if(uid!=null&&uid!=0) {
                baseUsers.get(i).setBaseRoles(baseRoleMapper.queryBaseRoleListByUid(uid));
            }else{
                baseUsers.get(i).setBaseRoles(new ArrayList<BaseRole>());
            }
        }
        return page.setRecords(baseUsers);
    }

    public int updateBaseUser(BaseUser baseUser) {
        BaseUser baseUser1 = baseUserMapper.loadUserByUsernameExit(baseUser);
        if (baseUser1 != null) {
            return -1;
        }
        return baseUserMapper.updateBaseUser(baseUser);
    }

    public int updateBaseUserBaseRoles(Long baseUserId, Long[] rids) {
        int i = baseUserMapper.deleteBaseRoleByBaseUserId(baseUserId);
        return baseUserMapper.addBaseRolesForBaseUser(baseUserId, rids);
    }

    public BaseUser getBaseUserById(Long baseUserId) {
        return baseUserMapper.getBaseUserById(baseUserId);
    }

    public int deleteBaseUser(Long baseUserId) {
        return baseUserMapper.deleteBaseUser(baseUserId);
    }

    @Override
    public List<BaseUser> selectBaseUserByMap(Map search) {
        return baseUserMapper.selectBaseUserByMap(search);
    }

    @Override
    public Integer selectCountAccount() {
        return baseUserMapper.selectCountAccount();
    }

    @Override
    public BaseCompany selectMapCompany(String id) {
        return baseUserMapper.selectMapCompany(id);
    }

    @Override
    public Integer getBaseUsersByEmployeeId(int employeeId) {
        return baseUserMapper.getBaseUsersByEmployeeId(employeeId);
    }

    public String hexpwd(String pwd, String npwd) {
        String salt = UUID.randomUUID().toString().substring(0, 6);
        System.out.println(SHA256Util.getSHA256StrJava("G1" + salt + pwd).length());//G1+随机数+密码进行SHA256运算
        Random random = new Random();
        int cycletimes = (int) (random.nextInt(100)) + 100;//后随机数范围变成[ 100~999）；循环次数
        System.out.println(cycletimes);
        String sh256 = "";
        sh256 = SHA256Util.getSHA256StrJava("G1" + salt + pwd);//G1+随机数+密码进行SHA256运算 循环多少次循环的次数是随机生成的
        for (int i = 0; i <= cycletimes; i++) {
            sh256 = SHA256Util.getSHA256StrJava("G1" + salt + pwd + sh256);//G1+随机数+密码进行SHA256运算 循环多少次循环的次数是随机生成的
            sh256 = sh256;
            //sh256=SHA256Util.getSHA256StrJava("G1"+cd+"123456");
            //System.out.println(sh256);
        }
        System.out.println(sh256);
        String hex = HexStringUtils.toHex("G1" + salt + cycletimes + sh256);//16进制字符串
        System.out.println("16进制字符串存数据库" + hex);
        return hex;
    }

    public String hexpwd1(String pwd, String npwd, String salt, int cycletimes) {
        System.out.println(SHA256Util.getSHA256StrJava("G1" + salt + pwd).length());
        Random random = new Random();
        String sh256 = "";
        sh256 = SHA256Util.getSHA256StrJava("G1" + salt + pwd);
        for (int i = 0; i <= cycletimes; i++) {
            sh256 = SHA256Util.getSHA256StrJava("G1" + salt + pwd + sh256);
            sh256 = sh256;
            ;
        }
        System.out.println(sh256);
        String hex = HexStringUtils.toHex("G1" + salt + cycletimes + sh256);//16进制字符串
        System.out.println("16进制字符串存数据库" + hex);
        return hex;
    }

    @Override
    public void relieveUnlock(String name) {
        baseUserMapper.relieveUnlock(name);
    }

    @Override
    @CachePut(value = "translate")
    public Integer saveTranslate(String username, Integer translate) {
        return translate;
    }
}
